from flask import Blueprint, render_template, request, jsonify,g
from sqlalchemy.orm import aliased

from exts import db
from models import DNew as Dtable,DCategory
admin_new = Blueprint('new',__name__,url_prefix='/new')

@admin_new.route('/index')
def index():
    where=[]
    page = int(request.args.get('page', '1'))
    key = request.args.get('key', '')
    cid = int(request.args.get('cid', '0'))

    if(key!=''):
        where.append(Dtable.title.like("%"+key+"%"))
    if (cid >0):
        where.append(Dtable.cid==cid)

    list= Dtable.query.join(DCategory, Dtable.cid == DCategory.id).filter(*where).order_by(Dtable.sort.desc(),Dtable.id.desc()).paginate(page=page, per_page=g.config['PAGE_NUM'])




    cate_list=DCategory.query.order_by(DCategory.sort.desc(),DCategory.id.desc()).all()

    data={
        'keys':{'key':key,'cid':cid},
        'data':list,
        'cate_list':cate_list
    }
    return render_template('admin/new/index.html',**data)

@admin_new.route('/add')
def add():
    cate_list = DCategory.query.order_by(DCategory.sort.desc(), DCategory.id.desc()).all()
    return render_template('admin/new/edit.html',info=None,cate_list=cate_list)

@admin_new.route('/edit')
def edit():
    id = request.args.get('id', '0')
    info = Dtable.query.filter(Dtable.id == id).first()
    cate_list = DCategory.query.order_by(DCategory.sort.desc(), DCategory.id.desc()).all()
    return render_template('admin/new/edit.html',info=info,cate_list=cate_list)

@admin_new.route('/save',methods=['POST'])
def save():
    post = request.form.to_dict()
    if post['id']=='0':
        post.pop('id')
        adddb = Dtable(**post)
        db.session.add(adddb)
        db.session.commit()
    else:
        Dtable.query.filter(Dtable.id == post['id']).update(post)
        db.session.commit()

    return jsonify({'code': 200, 'msg': "保存成功!"})


@admin_new.route('/dellete')
def delete():
    id = request.args.get('id', '0')
    Dtable.query.filter(Dtable.id == id).delete()
    db.session.commit()
    return jsonify({'code': 200, 'msg': "删除成功!"})

@admin_new.route('/status')
def status():
    id = int(request.args.get('id', 0))
    v = int(request.args.get('v', 0))
    Dtable.query.filter(Dtable.id == id).update({'status':abs(v-1)})
    db.session.commit()
    return jsonify({'code': 200, 'msg': "操作成功!"})